package xuegao.study.mall.web.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import xuegao.study.mall.common.api.CommonResult;
import xuegao.study.mall.common.constant.AuthConstant;
import xuegao.study.mall.common.domain.UserDto;
import xuegao.study.mall.common.service.RedisService;
import xuegao.study.mall.repo.dao.ums.UmsMemberDao;
import xuegao.study.mall.web.feign.Oauth2Client;
import xuegao.study.mall.web.service.UmsMemberService;
import xuegao.study.mall.common.model.ums.UmsMemberLevel;
import xuegao.study.mall.common.model.ums.UmsMember;
import xuegao.study.mall.web.feign.RbacServiceClient;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UmsMemberServiceImpl implements UmsMemberService {

    private Logger logger = LoggerFactory.getLogger(UmsMemberServiceImpl.class);

    @Autowired
    private RbacServiceClient rbacServiceClient;

    @Autowired
    private UmsMemberDao umsMemberDao;

    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;

    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Autowired
    private RedisService redisService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private Oauth2Client oauth2Client;

    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        // 验证码绑定手机号并存储到redis
        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);
        return CommonResult.success(sb.toString(), "获取验证码成功");
    }

    @Override
    public CommonResult verifyAuthCode(String telephone, String authCode) {
        if (StrUtil.isEmpty(authCode)) {
            return CommonResult.failed("请输入验证码");
        }
        String realAuthCode = (String) redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        boolean result = authCode.equals(realAuthCode);
        if (result) {
            return CommonResult.success(null, "验证码校验成功");
        } else {
            return CommonResult.failed("验证码不正确");
        }
    }

    @Override
    public void register(String username, String password, String telephone, String authCode) {
        // 1.验证码的验证逻辑

        // 2.查询该用户是否存在
        UmsMember umsMember = rbacServiceClient.loadUmsMemberByUserName(username);
        if (umsMember != null) {
            throw new RuntimeException("该用户已经存在");
        }
        // 3.没有该用户的话进行添加操作
        UmsMember member = new UmsMember();
        member.setUsername(username);
        member.setPassword(password);
        member.setPhone(telephone);
        member.setCreateTime(new Date());
        member.setStatus(1);
        // 4.设置会员等级
        UmsMemberLevel umsMemberLevel = rbacServiceClient.loadDefaultUmsMemberLevel();
        member.setMemberLevelId(umsMemberLevel.getId());
        rbacServiceClient.registerUmsMember(member);
    }

    @Override
    public CommonResult login(String username, String password) {
        //client_id和client_secret如何分配问题
        //针对会员,使用相同的client和client_secret
        Map<String, String> params = new HashMap<>();
        params.put("client_id", AuthConstant.PORTAL_CLIENT_ID);
        params.put("client_secret","123456");
        params.put("grant_type","password");
        params.put("username",username);
        params.put("password",password);
        return oauth2Client.getAccessToken(params);
    }

    @Override
    public UmsMember getCurrentMember() {
        String userStr = request.getHeader(AuthConstant.USER_TOKEN_HEADER);
        UserDto userDto = JSONUtil.toBean(userStr, UserDto.class);
        return getById(userDto.getId());
    }

    @Override
    public UmsMember getByUsername(String username) {
        return rbacServiceClient.loadUmsMemberByUserName(username);
    }

    @Override
    public UmsMember getById(Long id) {
        return umsMemberDao.selectById(id);
    }

    @Override
    public int updateIntegration(Long id, Integer integration) {
        UmsMember record = new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        return umsMemberDao.updateByPrimaryKey(record);
    }
}
